package com.iwhalecloud.citybrain.flow.platform.manager.application.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.iwhalecloud.citybrain.flow.platform.manager.application.common.enums.TaskLinkStatusEnum;
import com.iwhalecloud.citybrain.flow.platform.manager.application.common.threadlocal.CommonOperateLogHolder;
import com.iwhalecloud.citybrain.flow.platform.manager.common.client.HttpCommandDto;
import com.iwhalecloud.citybrain.flow.platform.manager.common.client.HttpCommandResultDto;
import com.iwhalecloud.citybrain.flow.platform.manager.common.client.HttpTaskListQueryDto;
import com.iwhalecloud.citybrain.flow.platform.manager.common.client.HttpTaskQueryInfoDto;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.model.app.FlowApp;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.model.monitor.FlowTaskTraceVo;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.model.monitor.HttpTaskQueryVo;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.repository.FlowAppRepository;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.repository.FlowTaskTraceRepository;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.repository.FlowTitleExpressionResultRepository;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.flowable.engine.HistoryService;
import org.flowable.variable.api.history.HistoricVariableInstance;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 待办/已办列表
 *
 * @author lilh
 * @date 2020/12/28 下午3:06
 */
@Component
public class QueryTaskCommandHandler extends AbstractCommandHandler {

    @Autowired
    private FlowTaskTraceRepository taskTraceRepository;

    @Autowired
    private FlowAppRepository appRepository;

    @Autowired
    private HistoryService historyService;

    @Autowired
    FlowTitleExpressionResultRepository flowTitleExpressionResultRepository;

    @Override
    public String handleType() {
        return TASK_LIST;
    }

    @Override
    public HttpCommandResultDto handle(String params) {
        HttpTaskListQueryDto taskListQueryDto = JSONObject.parseObject(params, HttpTaskListQueryDto.class);
        return handle(taskListQueryDto);
    }

    @Override
    public HttpCommandResultDto handle(HttpCommandDto commandDto) {
        HttpTaskListQueryDto taskListQueryDto = (HttpTaskListQueryDto) commandDto;
        CommonOperateLogHolder.getContent().setRequest(taskListQueryDto);
        if (StringUtils.isBlank(taskListQueryDto.getAssignee()) && StringUtils.isBlank(taskListQueryDto.getAppCode())) {
            return resolveFailResult(null, "assignee和appCode不能同时为空");
        }
        if (StringUtils.isBlank(taskListQueryDto.getType())) {
            taskListQueryDto.setType(TaskLinkStatusEnum.TODO.getCode());
        }
        if (!isValidType(taskListQueryDto)) {
            return resolveFailResult(null, "type参数取值错误，只能为['TODO','DONE']");
        }
        processPageParams(taskListQueryDto);

        HttpCommandResultDto result = resolveResult(null, "查询成功");
        doHandle(taskListQueryDto, result);
        return result;
    }

    private void doHandle(HttpTaskListQueryDto taskListQueryDto, HttpCommandResultDto result) {
        HttpTaskQueryVo taskQueryVo = new HttpTaskQueryVo();
        BeanUtils.copyProperties(taskListQueryDto, taskQueryVo);
        //这里需要再处理一下
        if (!processAppCodeAndCheckValid(taskListQueryDto, taskQueryVo)) {
            return;
        }

        logger.info("listTask queryVo:"+JSON.toJSONString(taskQueryVo));
        List<FlowTaskTraceVo> tasks = taskTraceRepository.listTaskWithProcessVariable(taskQueryVo);
        logger.error("listTaskWithProcessVariable result:"+JSON.toJSONString(tasks));
        PageInfo<FlowTaskTraceVo> pageTasks = new PageInfo<>(tasks);
        result.setPageNum(taskListQueryDto.getPageNum());
        result.setPageSize(taskListQueryDto.getPageSize());
        result.setTotalCount((int) pageTasks.getTotal());
        result.setDatas(tasks.stream().map(item -> {
            String processInstanceId = item.getProcessInstanceId();
            HttpTaskQueryInfoDto tmp = new HttpTaskQueryInfoDto();
            BeanUtils.copyProperties(item, tmp);
            //自定义标题
            tmp.setCustomTitle(flowTitleExpressionResultRepository.getTitleExpressionResultByProcessInstanceIdAndActivityId(processInstanceId,tmp.getActivityId()));
            return tmp;
        }).collect(Collectors.toList()));
        logger.info("after setVariables and title:"+ JSON.toJSONString(result));
    }

    private boolean processAppCodeAndCheckValid(HttpTaskListQueryDto taskListQueryDto, HttpTaskQueryVo taskQueryVo) {
        if (StringUtils.isNotBlank(taskListQueryDto.getAppCode())) {
            //查询appid
            List<FlowApp> apps = appRepository.listByAppCode(taskListQueryDto.getAppCode());
            if (CollectionUtils.isNotEmpty(apps) && Objects.nonNull(apps.get(0))) {
                taskQueryVo.setAppId(apps.get(0).getId());
            }
        }

//        if (Objects.isNull(taskQueryVo.getAppId())) {
//            logger.warn("传递的appCode无效");
//            return false;
//        }
        return true;
    }

    private boolean isValidType(HttpTaskListQueryDto taskListQueryDto) {
        return Objects.equals(taskListQueryDto.getType(), TaskLinkStatusEnum.TODO.getCode())
                || Objects.equals(taskListQueryDto.getType(), TaskLinkStatusEnum.DONE.getCode());
    }

}
